home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 4512 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  57 lines

  1. Path: solon.com!not-for-mail
  2. From: seebs@solutions.solon.com (Peter Seebach)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: ???Recursive Function needed for string printing
  5. Date: 5 Feb 1996 07:57:20 -0600
  6. Organization: Usenet Fact Police (Undercover)
  7. Message-ID: <4f52c0$6de@solutions.solon.com>
  8. References: <4f44eo$74u@upsidedown.MTS.Net>
  9. NNTP-Posting-Host: solutions.solon.com
  10.  
  11. In article <4f44eo$74u@upsidedown.MTS.Net>, George <bwilliam@MTS.Net> wrote:
  12. >How do I write a recursive function to print a string  using only
  13. >printf and %c to print it out.
  14.  
  15. Since you need a %s to print a string, of course, you really need a function
  16. to recursively create a %s without using it in the code.  This should work
  17. just fine:
  18.  
  19. #include <stdio.h>
  20.  
  21. int far(int, char *); /* prototype our function to print a string */
  22.  
  23. int
  24. main(int argc, char **argv) {
  25.     return far(0, argc > 1 ? argv[1] : "test string");
  26. }
  27.  
  28. /* set up format string. */
  29. enum {
  30.     ONE = 0x0, NUL = 0x1, NEW = 11, PERCENT = 0x26, ESS = 0x74
  31. } fmt[] = {
  32.     PERCENT, ESS, NEW, NUL, ONE
  33. };
  34.  
  35. /* far: print a string.
  36.  * we take two paramaters, "near" -> how close we are to finished,
  37.  * "s", the string to print.
  38.  * we recurse through fmt building a format string in buf, then use
  39.  * it to print our string.
  40.  */
  41. int
  42. far(int near, char *s) {
  43.     static char buf[5];
  44.  
  45.     if (fmt[near]) {
  46.         buf[near] = fmt[near] - 1; /* the previous item */
  47.         far(near + 1, s); /* recursion */
  48.     }
  49.     return near ? 1 : !printf(buf, s);
  50. }
  51.  
  52. -- 
  53. Peter Seebach - seebs@solon.com - Copyright 1995 Peter Seebach.
  54. C/Unix wizard -- C/Unix questions? Send mail for help.  No, really!
  55. Using trn?  Weird new newsgroup problem?  I know the fix!  Email me!
  56. The *other* C FAQ - ftp taniemarie.solon.com /pub/c/afq - Not A Flying Toy
  57.